/*
 * hb-autologin - Login to University College of Borås pages automatically
 * Version: 0.1.1
 * Author: David Laurell <david.laurell@gmail.com>
 * License: GPLv3
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 */

function getField(type, form) {
	var inputs = form.getElementsByTagName("input");
	for(var i=0;i<inputs.length;i++) {
		if(inputs[i].getAttribute("type").toLowerCase() == type)
			return inputs[i];
	}
	return false;
}

chrome.extension.sendRequest({msg: "get"}, function(response) {
	var usernameField, passwordField;
	var data = response.login;
	var forms = document.getElementsByTagName("form");

	for(i=0;i<forms.length; i++) {
		usernameField = getField("text", forms[i]);
		passwordField = getField("password", forms[i]);

		if(usernameField && passwordField) {
			if(data.username && data.password) {
				usernameField.value = data.username;
				passwordField.value = data.password;
				forms[i].submit();
			}
			else {
				if(confirm("Autologin on University College of Borås web sites failed because you haven't configured a username and password. Want to do that now?"))
					chrome.extension.sendRequest({msg: "showOptions"});
			}
			break;
		}		
	}


});
